package com.asus.studyproject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;


/**
 * Created by asus1 on 2017/10/15.
 */

public class mBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "广播接受者已察觉网络状态改变", Toast.LENGTH_SHORT).show();

        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                context.startService(new Intent(context, MyService.class));
                return;
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                context.startService(new Intent(context, MyService.class));
                return;
            } else {
                context.stopService(new Intent(context, MyService.class));
                return;
            }
        }
        context.stopService(new Intent(context, MyService.class));
    }
}
